//
//  BLNetworkListener.m
//  BL
//
//  Created by Benz.L on 16/6/3.
//  Copyright © 2016年 benzii.com All rights reserved.
//

#import "BLNetworkListener.h"
#import "Reachability.h"

@interface BLNetworkListener ()
//@property(nonatomic, strong) NSLock *lock;
@property(nonatomic, strong) Reachability *reachability;
@property(nonatomic, strong) FlutterMethodChannel  *channel;
@end

@implementation BLNetworkListener

- (void)dealloc {
    [_reachability stopNotifier];
    _reachability.reachableBlock = nil;
    _reachability.unreachableBlock = nil;
}

- (instancetype)initWithChannel:(FlutterMethodChannel *)channel {
    self = [super init];
    if (self) {
        self.channel = channel;
        [self.reachability startNotifier];
//        [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            [self reachabilityDidChanged:self.reachability];
//        }];
    }
    return self;
}

- (void)fetchStatus:(FlutterMethodCall *)call result:(FlutterResult)result {
    result(@(self.reachability.currentReachabilityStatus));
}

#pragma mark -- 实现FlutterPlatformViewFactory 的代理方法
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
    return [FlutterStandardMessageCodec sharedInstance];
}

#pragma mark - Private

- (Reachability *)reachability {
    if (!_reachability) {
        //不使用通知方式监听网络状态变化，因为其他人也有可能使用Reachability直接初始化对象，会出现多次接收通知事件
        Reachability *bility = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//        Reachability *bility = [Reachability reachabilityForInternetConnection];
        __weak typeof(self) weak = self;
        bility.reachableBlock = ^(Reachability *objc) {
            __strong typeof(weak) strong = weak;
            [strong reachabilityDidChanged:objc];
        };
        bility.unreachableBlock = ^(Reachability *objc) {
            __strong typeof(weak) strong = weak;
            [strong reachabilityDidChanged:objc];
        };
        _reachability = bility;
    }
    return _reachability;
}

//- (NSLock *)lock {
//    if (!_lock) {
//        _lock = NSLock.new;
//    }
//    return _lock;
//}

- (void)reachabilityDidChanged:(Reachability *)obj {
    NetworkStatus status = obj.currentReachabilityStatus;
    [self.channel invokeMethod:@"didChanged" arguments:@(status)];
}

@end
